from rest_framework import serializers
from django.db.models import Count, Min, Max
from .models import ErrorLog

class ErrorLogSerializer(serializers.ModelSerializer):
    project_name = serializers.CharField(source='project.name', read_only=True)
    count = serializers.SerializerMethodField()
    firstSeen = serializers.SerializerMethodField()
    lastSeen = serializers.SerializerMethodField()
    
    class Meta:
        model = ErrorLog
        fields = [
            'id', 'project', 'project_name', 'level', 'message', 
            'stack_trace', 'timestamp', 'user_agent', 'ip_address', 'url',
            'fingerprint', 'source', 'user_id', 'session_id', 'count',
            'firstSeen', 'lastSeen', 'environment', 'request_info',
            'breadcrumbs', 'performance', 'context'
        ]
        read_only_fields = ['id', 'timestamp', 'fingerprint']
    
    def get_count(self, obj):
        """获取相同指纹的错误数量"""
        return ErrorLog.objects.filter(
            fingerprint=obj.fingerprint,
            project=obj.project
        ).count()
    
    def get_firstSeen(self, obj):
        """获取首次发现时间"""
        first_log = ErrorLog.objects.filter(
            fingerprint=obj.fingerprint,
            project=obj.project
        ).order_by('timestamp').first()
        return first_log.timestamp.isoformat() if first_log else obj.timestamp.isoformat()
    
    def get_lastSeen(self, obj):
        """获取最后发现时间"""
        last_log = ErrorLog.objects.filter(
            fingerprint=obj.fingerprint,
            project=obj.project
        ).order_by('-timestamp').first()
        return last_log.timestamp.isoformat() if last_log else obj.timestamp.isoformat()

class ErrorLogCreateSerializer(serializers.ModelSerializer):
    """创建错误日志的序列化器"""
    
    class Meta:
        model = ErrorLog
        fields = [
            'project', 'level', 'message', 'stack_trace', 
            'user_agent', 'ip_address', 'url', 'source', 'user_id', 'session_id',
            'environment', 'request_info', 'breadcrumbs', 'performance', 'context'
        ]